from flask import g
from flask import render_template, current_app, jsonify
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.modules.index import index_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET


@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """

    # 1. 获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2. 校验数据
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = []
    if cid != "1":
        # 需要添加条件
        filters.append(News.category_id == cid)
    # 3. 查询数据
    filters = [News.status == 0]
    # 如果分类id不为0, 那么添加分类id的过滤
    if News.category_id != 0:
        filters.append(News.category_id == News.category_id)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 取到当前页的数据
    news_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转换成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())



    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_dict_li":news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

@index_blu.route('/')
@user_login_data
def index():
    # # 获取当前登录用户的id
    # user_id = session.get("user_id", None)
    # # 通过id获取用户信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as ret:
    #         current_app.logger.error(ret)

    user = g.user

    # 右侧新闻排行逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as ret:
        current_app.logger.error(ret)
    news_dict_li = []
    for news in news_list if news_list else []:
        news_dict_li.append(news.to_basic_dict())

    # 查询分类数据
    Categories = Category.query.all()
    category_li = []
    for category in Categories:
        category_li.append(category.to_dict())


    data = {
        "user":user.to_dict() if user else None,
        "news_dict_li":news_dict_li,
        "category_li": category_li
    }

    return render_template("/news/index.html", data=data)





# 在打开网页的时候, 浏览器会默认去请求跟路径+favicon.ico做网站标签的小图标
# send_static_file 是flask 去直接指定的静态文件所调用的方法
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")